import { _decorator, Component, Node, Sprite, resources, SpriteFrame, UITransform, Layers } from 'cc'
const { ccclass, property } = _decorator

// 瓦片的宽高
export const TILE_WIDTH = 55
export const TILE_HEIGHT = 55

import { TileManager } from './TileManager'
import { createUINode, random } from '../../Utils'

// 引入单例
import DataManager from '../../Runtime/DataManager'
import RescourceManager from '../../Runtime/RescourceManager'

@ccclass('TileMapManager')
export class TileMapManager extends Component {
  async init() {
    // 先等加载资源
    const spriteFrames = await RescourceManager.Instance.loadDir('texture/tile/tile', SpriteFrame)

    const mapInfo = DataManager.Instance.mapInfo
    DataManager.Instance.tileInfo = []

    mapInfo.forEach((row, i) => {
      DataManager.Instance.tileInfo[i] = []
      row.forEach((tile, j) => {
        const { src, type } = tile
        if (src === null || type === null) {
          return
        }



        // 随机树
        let num = src
        if ([1, 5, 9].indexOf(num) > -1 && i % 2 === 0 && j % 2 === 0) {
          const randomNum = random(0, 4)
          num += randomNum
        }

        // 通过名字去匹配
        const imgSrc = `tile (${num})`
        // 防止找不到就使用第一个图片
        const spriteFrame = spriteFrames.find(frame => frame.name === imgSrc) || spriteFrames[0]

        // 初始化瓦片
        // 生成节点
        const node = createUINode()
        const tileManager = node.addComponent(TileManager)
        tileManager.init({ type, spriteFrame, i, j })

        // 添加到舞台
        this.node.addChild(node)

        // 保存瓦片信息
        DataManager.Instance.tileInfo[i][j] = tileManager
      })
    })
  }

  // // 加载资源
  // loadResources() {
  //   return new Promise<SpriteFrame[]>((resolve, reject) => {
  //     // 加载图片资源
  //     resources.loadDir('texture/tile/tile', SpriteFrame, function (err, assets) {
  //       if (err) {
  //         reject(err)
  //       } else {
  //         resolve(assets as SpriteFrame[])
  //       }
  //     })
  //   })
  // }
}
